package com.oreilly.android.taskmanager;

import java.util.ArrayList;

import com.oreilly.android.taskmanager.tasks.Task;
import com.oreilly.android.taskmanager.tasks.TasksSQLiteOpenHelper;
import static com.oreilly.android.taskmanager.tasks.TasksSQLiteOpenHelper.*;

import android.app.Application;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class TaskManagerApplication extends Application {

	private TaskManagerLocationManager locationManager;

	private ArrayList<Task> allTasks;
	private SQLiteDatabase database;

	// public static final String TASK_ID = "TASK_ID";

	@Override
	public void onCreate() {
		super.onCreate();
		TasksSQLiteOpenHelper helper = new TasksSQLiteOpenHelper(this);
		database = helper.getWritableDatabase();
		if (null == allTasks) {
			loadTasks();
		}

		locationManager = new TaskManagerLocationManager(this);
	}

	@Override
	public void onTerminate() {
		database.close();
		super.onTerminate();
	}

	public ArrayList<Task> getAllTasks() {
		return allTasks;
	}

	public void setAllTasks(ArrayList<Task> allTasks) {
		this.allTasks = allTasks;
	}

	public void addTask(Task t) {
		ContentValues values = buildValues(t);
		Log.d("TaskManager", "Adding task: " + t.toString());
		Long id = database.insert(TASKS_TABLE, null, values);
		t.setId(id);

		allTasks.add(t);
	}

	public void saveTask(Task t) {
		ContentValues values = buildValues(t);

		long id = t.getId();
		String where = String.format("%s = %d", TASK_ID, id);
		database.update(TASKS_TABLE, values, where, null);
		Task task = findTask(t.getId());
		task = t;
	}

	public void deleteTask(long id) {
		String where = String.format("%s in (%s)", TASK_ID, id);
		database.delete(TASKS_TABLE, where, null);
	}

	public void deleteTasks(Long[] ids) {
		StringBuffer idList = new StringBuffer();
		for (int i = 0; i < ids.length; i++) {
			idList.append(ids[i]);
			if (i < ids.length - 1) {
				idList.append(",");
			}
		}

		String where = String.format("%s in (%s)", TASK_ID, idList);
		database.delete(TASKS_TABLE, where, null);
	}

	public Task findTask(long id) {
		for (Task t : allTasks) {
			if (t.getId() == id)
				return t;
		}

		return null;
	}

	protected void loadTasks() {
		allTasks = new ArrayList<Task>();
		String[] columns = new String[] { TASK_ID, TASK_TITLE,
				TASK_DESCRIPTION, TASK_COMPLETE, TASK_DUE_DATE, TASK_LATITUDE,
				TASK_LONGITUDE };

		Cursor tasksCursor = database.query(TASKS_TABLE, columns, null, null,
				null, null, String.format("%s,%s", TASK_COMPLETE, TASK_TITLE));

		Task t;
		while (tasksCursor.moveToNext()) {
			long id = tasksCursor.getInt(0);
			String name = tasksCursor.getString(1);
			String description = tasksCursor.getString(2);
			String boolValue = tasksCursor.getString(3);
			// due date
			float latitude = tasksCursor.getFloat(5);
			float longitude = tasksCursor.getFloat(6);

			boolean complete = Boolean.parseBoolean(boolValue);

			t = new Task(name);
			t.setId(id);
			t.setDescription(description);
			t.setComplete(complete);
			// due date
			t.setLatitude(latitude);
			t.setLongitude(longitude);
			allTasks.add(t);
		}
		tasksCursor.close();
	}

	protected ContentValues buildValues(Task t) {
		ContentValues values = new ContentValues();
		values.put(TASK_TITLE, t.getTitle());
		values.put(TASK_DESCRIPTION, t.getDescription());
		// values.put(TASK_DUE_DATE, t.getDueDate().toGMTString());
		values.put(TASK_COMPLETE, Boolean.toString(t.isComplete()));
		values.put(TASK_LATITUDE, t.getLatitude());
		values.put(TASK_LONGITUDE, t.getLongitude());
		values.put(TASK_LOCATION, t.getLocation());
		return values;
	}

	/**
	 * @return the locationManager
	 */
	public TaskManagerLocationManager getLocationManager() {
		return locationManager;
	}

	/**
	 * @param locationManager
	 *            the locationManager to set
	 */
	public void setLocationManager(TaskManagerLocationManager locationManager) {
		this.locationManager = locationManager;
	}

}
